
<div style="margin: 10px 10px 10px 10px">
    <form class="layui-form layui-form-pane" action="">
        <div class="layui-form-item">
              <div class="layui-inline">
                <div class="layui-input-inline">
                  <input id="s_time" type="text" name="s_time" lay-verify="required"  placeholder="开始时间" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline">
                <div class="layui-input-inline">
                  <input id="e_time" type="text" name="e_time" lay-verify="required"  placeholder="结束时间" autocomplete="off" class="layui-input">
                </div>
              </div>
              <div class="layui-inline">
                <div class="layui-input-inline">
                  <select name="chose_time" >
                    <option value="0">自定义查询时间</option>
                    <option value="1">1天</option>
                    <option value="7">7天</option>
                    <option value="15">15天</option>
                    <option value="30">30天</option>
                  </select>
                </div>
              </div>
            <div class="layui-inline" >
              <div class="layui-input-inline" style="width: 300px">
                <select name="chose_device" id="chose_device" xm-select="select" xm-select-type="1"  xm-select-search="" xm-select-height="36px" >
                </select>
              </div>
            </div>
            <div class="layui-inline">
                <a class="layui-btn" lay-submit="" lay-filter="data-search-btn">查询</a>
            </div>
        </div>
    </form>
</div>
<!-- 健康数据表格开始 -->
<table class="layui-table" id="health_report_table" lay-filter="health_report_table"></table>
<script type="text/html" id="health_report_bar">
    <a class="layui-btn layui-btn-xs " lay-event="show_health_detail">图表展示</a>
</script>
<!-- 健康数据表格结束 -->
<!-- e_chart部分开始 -->
<div class="layui-coutainer" style="display:none" id="echarts_div">
 <div class="layui-row" >
  <!-- 雷达图开始 -->
  <div class="layui-col-lg6">
    <div class="layui-row " style="padding: 5px; background-color: #F2F2F2;">
      <div class="layui-col-md12">
        <div class="layui-card">
          <!-- <div class="layui-card-header">健康数据雷达图</div> -->
          <div class="layui-card-body" style="text-align: center;">
             <div  id="radar_chart"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
   
  <div class="layui-col-lg6" >
    <div class="layui-row " style="padding: 5px; background-color: #F2F2F2;">
      <div class="layui-col-md12">
        <div class="layui-card" >
          <!-- <div class="layui-card-header">人员基本信息</div> -->
          <div class="layui-card-body" style="">
             <div class="layui-row" id="person_base_info">
              <div class="layui-col-md6">
                <div class="layui-card" style="">
                  
                  <div class="layui-card-body" id="p_name">
                    姓名：
                  </div>
                   <div class="layui-card-body" id="p_sex">
                    性别：
                  </div>
                  <div class="layui-card-body" id="p_age">
                    年龄：
                  </div>
                  <div class="layui-card-body" id="p_department">
                    部门：
                  </div>
                </div>
              </div>
              <div class="layui-col-md6">
                <div class="layui-card">
                  
                  <div class="layui-card-body">
                    <img src="/static/img/person_default.png" style="width: 120px;height: 160px" id="p_picture">
                  </div>
                </div>
              </div>
              <div class="layui-col-md12">
                <div class="layui-card">
                  <div class="">
                    附加信息：
                  </div>
                  <div class="">
                    备注信息：
                  </div>
                </div>
              </div>
            </div>
        </div>
      </div>
    </div>
  </div>
  </div>
  <!-- 曲线图 -->
  <div class="layui-row ">
    <div class="layui-col-md12" >
      <div class="layui-card">
        <!-- <div class="layui-card-header">健康数据详情</div> -->
        <div class="layui-card-body">
           <div  id="report_data_detail" style="width:100%;height:250px"></div>
        </div>
      </div>
    </div>
  </div>
</div>
</div>
<!-- e_chart部分结束 -->
<!-- js代码开始 -->
<!-- 引用echart插件 -->
<script src="/static/echartsjs/echarts.min.js"></script>
<script type="text/javascript">

form.render()
// 图标的宽度和高度的适应屏幕处理
var radar_chart_width=get_width/3
var radar_chart_height=get_height/2.6
$('#radar_chart').attr('style','height:'+radar_chart_height+'px;width:'+radar_chart_width+'px;')
$('#person_base_info').attr('style','height:'+radar_chart_height+'px;width:'+radar_chart_width+'px;')
var report_data_detail_height=get_height-radar_chart_height-100
var report_data_detail_width=get_width/1.1
$('#report_data_detail').attr('style','height:'+report_data_detail_height+'px;width:'+report_data_detail_width+'px;')

// 默认加载设备数据表格渲染函数
var table_show=function(table_data){
  table.render({
    elem: '#health_report_table',
    data: table_data,
    toolbar: true,
    title:'健康数据',
    id:'device_table',
    cols: [
    [   {field: 'user_name', title: '名称',sort:true,templet:function(d){
          
          var dev_detail=get_detail_from_id(device,d.device_id)
          var user_name=dev_detail.user_name
          if(dev_detail.user_detail!=0 && dev_detail.user_detail!='0'){
            user_name=dev_detail.user_detail.name
          }
          return user_name
        }},
        {field: 'device_id', title: '设备ID',sort:true},
        {field: 'heart_rate', title: '心率',sort:true,templet:function(d){
          return d.heart_rate+' 次/min'
        }},
        {field: 'blood_pres', title: '血压',sort:true,templet:function(d){
          var blood_pres,h_pres,l_pres;
          if(d.blood_pres!=null){
            if(d.blood_pres!='0'){
              blood_pres=eval('('+d.blood_pres+')')
            }else{
              blood_pres={'h_pres':'0','l_pres':'0'};
            }
            l_pres=blood_pres['l_pres']
            h_pres=blood_pres['h_pres']
          }else{
            l_pres=d.l_pres;
            h_pres=d.h_pres
          }
          return '收缩压：'+h_pres+','+'舒张压：'+l_pres
        }},
        {field: 'step_count', title: '步数',sort:true,templet:function(d){
          return d.step_count+'步'
        }},
        {field: 'stop_time', title: '静止时长',sort:true,templet:function(d){
          var stop_time=(parseInt(d.stop_time)/60).toFixed(1)
          return stop_time+'分钟'
        }},
        {field: 'sleep', title: '睡眠时长',sort:true,templet:function(d){
          var sleep_time=d.sleep;
          if(sleep_time!=='0'){
            sleep_time=eval('('+sleep_time+')')
            sleep_time=((sleep_time['sleep_time']+sleep_time['light_sleep_time'])/60).toFixed(1)
          }
          return sleep_time+'分钟'
        }},
        {field: 'analysis_time', title: '统计时间',sort:true},
        // {title: '操作',templet: '#health_report_bar', fixed: "right", align: "center"}
    ]],
    limits: [10, 15, 20, 25, 50, 100],
    limit: 10,
    page: true
  });
}

// 首次健康数据加载
var get_daily_reports=function(){

   $.ajax({
          type: 'GET',
          url:"/health_reports/?what="+'get_health_reports',
          dataType: 'json',
          success: function( data) {
          console.log(data)
          table_show(data)
        },
        error:function (edata) {
              console.log(edata)
          }
      }); 

}
$(function(){
  get_daily_reports()
})
      

// 查询设备数据表格渲染函数
var detail_table_show=function(table_data){
  table.render({
    elem: '#health_report_table',
    data: table_data,
    toolbar: true,
    title:'健康数据',
    id:'device_table',
    cols: [
    [   {field: 'user_name', title: '名称',sort:true,templet:function(d){
          
          var dev_detail=get_detail_from_id(device,d.device_id)
          var user_name=dev_detail.user_name
          if(dev_detail.user_detail!=0 && dev_detail.user_detail!='0'){
            user_name=dev_detail.user_detail.name
          }
          return user_name
        }},
        {field: 'device_id', title: '设备ID',sort:true},
        {field: 'heart_rate', title: '心率',sort:true,templet:function(d){
          return d.heart_rate+' 次/min'
        }},
        {field: 'blood_pres', title: '血压',sort:true,templet:function(d){
          var blood_pres,h_pres,l_pres;
          if(d.blood_pres!=null){
            if(d.blood_pres!='0'){
              blood_pres=eval('('+d.blood_pres+')')
            }else{
              blood_pres={'h_pres':'0','l_pres':'0'};
            }
            l_pres=blood_pres['l_pres']
            h_pres=blood_pres['h_pres']
          }else{
            l_pres=d.l_pres;
            h_pres=d.h_pres
          }
          return '收缩压：'+h_pres+','+'舒张压：'+l_pres
        }},
        {field: 'step_count', title: '步数',sort:true,templet:function(d){
          return d.step_count+'步'
        }},
        {field: 'stop_time', title: '静止时长',sort:true,templet:function(d){
          var stop_time=(parseInt(d.stop_time)/60).toFixed(1)
          return stop_time+'分钟'
        }},
        {field: 'sleep', title: '睡眠时长',sort:true,templet:function(d){
          var sleep_time=d.sleep;
          if(sleep_time==null){
            sleep_time=d.sleep_time
          }
          sleep_time=(parseInt(sleep_time)/60).toFixed(1)
          return sleep_time+'分钟'
        }},
        // {field: 'analysis_time', title: '更新时间',sort:true},
        {title: '操作',templet: '#health_report_bar', fixed: "right", align: "center"}
    ]],
    limits: [10, 15, 20, 25, 50, 100],
    limit: 10,
    page: true
  });
}

// 健康数据查询的ajax

var health_reports_ajax=function(query_param,query_detail){

  var wait_for_ready = layer.load(1);
   
   query_param=JSON.stringify(query_param)
   console.log(query_param)
   $.ajax({
          type: 'POST',
          url:"/health_reports/?what="+'health_reports',
          dataType: 'json',
          async:true,
          data:{query_param},
          success: function( data) {
            console.log(data)
            detail_table_show(data)
            layer.msg('数据加载完成')
            layer.close(wait_for_ready); 
        },
        error:function (edata) {
              console.log(edata)
          }
      }); 
}


// 监听设备搜索操作
form.on('submit(data-search-btn)', function (data) {
  var search_key = data.field;
  var s_time=search_key['s_time'];
  var e_time=search_key['e_time'];
  // console.log(formSelects.value('select', 'val'))
  query_param={'hard_id':formSelects.value('select', 'val'),'s_time':s_time,'e_time':e_time,'chose_time':search_key['chose_time']}
  health_reports_ajax(query_param,'table')
  return false;
});
// 监听图表展示按钮
table.on('tool(health_report_table)',function(obj){
  console.log(obj)
  layer.open({
        type: 1
        ,title:'健康数据展示:'
        ,area:['100%','100%'] 
        ,offset:'60px'
        ,id: 'health_reports_chart' //防止重复弹出
        ,content:$('#echarts_div')
        ,zIndex:999
        ,success:function(layero){
          show_chart(obj.data)
          var dev_detail=get_detail_from_id(device,obj.data.device_id)
          var user_detail=dev_detail.user_detail
          var dev_user_name=dev_detail.user_name;
          var user_sex='',user_department='',user_character='',user_age='',user_picture='';
          if(user_detail!='0' | user_detail!=0){
            user_sex=user_detail.sex
            var person_detail=eval('('+user_detail.person_detail+')')
            console.log(person_detail)
            user_department=person_detail.department
            user_character=person_detail.character
            user_age=person_detail.person_age
            user_picture=person_detail.picture
            dev_user_name=user_detail.name
          }
          if(user_picture==='' | user_picture==null){
            user_picture='/static/img/person_default.png'
          }
          $('#p_name').text('姓名：'+dev_user_name)
          $('#p_sex').text('性别：'+user_sex)
          $('#p_age').text('年龄：'+user_age)
          $('#p_department').text('部门：'+user_department)
          $('#p_picture').attr('src',user_picture)

        }
        ,shade: 0 //不显示遮罩

        
      });
})
// 图标展示功能函数

var show_chart=function(device_data){
  var radar_value=[]
  radar_value.push(device_data['step_count'])
  radar_value.push(device_data['stop_time']/3600)
  if(device_data.sleep_time!=null){
    radar_value.push(device_data['sleep_time']/3600)
  }else{
    radar_value.push(device_data['sleep']/3600)
  }
  radar_value.push(device_data['heart_rate'])
  if(device_data.blood_pres!=null){
    if(device_data.blood_pres!='0'){
      radar_value.push(device_data['blood_pres']['l_pres'])
      radar_value.push(device_data['blood_pres']['h_pres'])
    }else{
      radar_value.push(0)
      radar_value.push(0)
    }
  }else{
    radar_value.push(device_data['l_pres'])
    radar_value.push(device_data['h_pres'])
  }
  
  radar_name_list=['运动步数','停留时长','睡眠时长','平均心率','收缩压','舒张压']
  console.log(radar_value)
  // 基于准备好的dom，初始化echarts实例
  var radar_chart = echarts.init(document.getElementById('radar_chart'));
  // 指定图表的配置项和数据
  var option = {
      tooltip: {trigger: 'item',},   
      legend: {formatter:function(name){return name},left:10,},
      radar: [{indicator: [
                  { name: '运动步数', max: 20000 },
                  { name: '停留时长', max: 24 },
                  { name: '睡眠时长', max: 12 },
                  { name: '平均心率', max: 160 },
                  { name: '舒张压', max: 112 },
                  { name: '收缩压', max: 175 }
              ],
              center: ['70%', '50%'],
              radius: 90
          }
      ],
      series: [{name: '健康数据',type: 'radar',areaStyle: {},data: [{value: radar_value,name:'健康数据雷达图'}]}]
  }
  radar_chart.setOption(option);

  // ---底部的曲线图----//
  var show_field=['sex','name','picture','department','worknumber','job','phone','character']
  var show_field_dict={'sex':'性别','name':'姓名','picture':'照片','department':'部门','worknumber':'编号','job':'职位','character':'编制','phone':'电话'}
  var input
  option1 = {
      title: {text: '健康数据详情'},
      tooltip: {trigger: 'axis'},
      legend: {
          data:['运动步数','心率','停留时长','睡眠时长','收缩压','舒张压'],
          selected:{'运动步数':false,'心率':false,'停留时长':false,'睡眠时长':false,'收缩压':false,'舒张压':false}
      },
      toolbox: {show: true,feature: {dataZoom: {yAxisIndex: 'none'},dataView: {readOnly: false},magicType: {type: ['line', 'bar']},restore: {},saveAsImage: {}}},
      xAxis:  {type: 'category',boundaryGap: false,data: []},
      yAxis: {type: 'value',},
      series: [
          {name:'运动步数',type:'line',data:[],markPoint: {data: [{type: 'max', name: '最大值'},{type: 'min', name: '最小值'}]},markLine: {data: [{type: 'average', name: '平均值'}]}},
          {name:'心率',type:'line',data:[],markPoint: {data: [{type: 'max', name: '最大值'},{type: 'min', name: '最小值'}]},markLine: {data: [{type: 'average', name: '平均值'}]}},
          {name:'停留时长',type:'line',data:[],markPoint: {data: [{type: 'max', name: '最大值'},{type: 'min', name: '最小值'}]},markLine: {data: [{type: 'average', name: '平均值'}]}},
          {name:'睡眠时长',type:'line',data:[],markPoint: {
                  data: [
                      {type: 'max', name: '最大值'},
                      {type: 'min', name: '最小值'}
                  ]
              },
              markLine: {
                  data: [
                      {type: 'average', name: '平均值'}
                  ]
              }
          },
          {name:'收缩压',type:'line',data:[],markPoint: {
                  data: [
                      {type: 'max', name: '最大值'},
                      {type: 'min', name: '最小值'}
                  ]
              },
              markLine: {
                  data: [
                      {type: 'average', name: '平均值'}
                  ]
              }
          },
          {name:'舒张压',type:'line',data:[],markPoint: {
                  data: [
                      {type: 'max', name: '最大值'},
                      {type: 'min', name: '最小值'}
                  ]
              },
              markLine: {
                  data: [
                      {type: 'average', name: '平均值'}
                  ]
              }
          }
      ]

  };

  var detail_chart = echarts.init(document.getElementById('report_data_detail'),{
      width: 'auto',
      height: report_data_detail_height-150
  });


  option1['series'][0]['data']=device_data['step_count_yAxis']
  option1['xAxis']['data']=device_data['step_count_xAxis']
  option1['title']['text']='运动步数'
  option1['legend']['selected']['运动步数']=true
  detail_chart.setOption(option1) 

  detail_chart.on('legendselectchanged', function (params) {
    console.log(params['name']);
    report_data_detail_dict={'运动步数':['step_count_xAxis','step_count_yAxis'],
                             '心率':['heart_rate_xAxis','heart_rate_yAxis'],
                             '停留时长':['stop_time_xAxis','stop_time_yAxis'],
                             '睡眠时长':['sleep_time_xAxis','sleep_time_yAxis'],
                             '收缩压':['h_pres_xAxis','h_pres_yAxis'],
                             '舒张压':['l_pres_xAxis','l_pres_yAxis']}
      
    var key_xaxis=report_data_detail_dict[params['name']][0]
    var key_yaxis=report_data_detail_dict[params['name']][1]

    option1['xAxis']['data']=device_data[key_xaxis]
    for(var i=0;i<option1['series'].length;i++){
      if(option1['series'][i]['name']==params['name']){
        option1['series'][i]['data']=device_data[key_yaxis]
        // option1['legend']['selected'][params['name']]=true
        for(var k in option1['legend']['selected']){
          if(k==params['name']){
            option1['legend']['selected'][params['name']]=true
          }else{
            option1['legend']['selected'][k]=false
          }
        }
        option1['title']['text']=params['name']
      }
    }
    detail_chart.setOption(option1) 
  });

  detail_chart.setOption(option1)

}

//添加选择设备列表
$(function(){ 
  $('#chose_device').empty()
  for (var i = device.length - 1; i >= 0; i--) {
    var user_name=device[i]['user_name'];
    if(device[i]['user_detail']!='0'){
      user_name=device[i].user_detail.name
    }
    var option='<option value="'+device[i]['device_id']+'">'+user_name+'</option>'
  $('#chose_device').append(option)
  }
  formSelects.render()
}); 

// 时间选择框渲染
laydate.render({
  elem: '#s_time'
  ,type: 'datetime'
  ,value:new Date(new Date(new Date().toLocaleDateString()).getTime())
  ,btns: ['clear','now', 'confirm']
});

laydate.render({
  elem: '#e_time'
  ,type: 'datetime'
  ,value:new Date()
  ,btns: ['clear','now', 'confirm']
});

</script>